<template>
  <div class="main-container">
    <!-- 右上角导航栏 -->
    <NavBar @view-history-questionnaire="viewHistoryQuestionnaire" />

    <!-- 来访者主页 -->
    <div v-if="role === 'VISITOR'" class="visitor-main">
      <h2>咨询师列表</h2>
      <div class="filter">
        <label for="region">选择地区:</label>
        <select v-model="selectedRegion" @change="filterConsultants">
          <option value="all">全部</option>
          <option v-for="region in regions" :key="region" :value="region">{{ region }}</option>
        </select>
        <label for="expertise">选择专长领域:</label>
        <select v-model="selectedExpertise" @change="filterConsultants">
          <option value="all">全部</option>
          <option v-for="expertise in expertises" :key="expertise" :value="expertise">{{ expertise }}</option>
        </select>
      </div>

      <div class="consultants">
        <div v-for="consultant in filteredConsultants" :key="consultant.id" class="consultant-card">
          <img :src="consultant.imgPath || 'default-avatar.png'" alt="Consultant" class="consultant-image" />
          <div class="consultant-details">
            <h3>{{ consultant.nickname }}</h3>
            <p>{{ consultant.goodAt }}</p>
            <p>{{ consultant.wage }}</p>
            <div class="consultant-actions">
              <button @click="chatWithConsultant(consultant.id)">聊天</button>
              <button @click="bookAppointment(consultant.id)">预约</button>
              <button @click="viewConsultant(consultant)">查看</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 查看历史问卷弹窗 -->
    <div v-if="showHistoryQuestionnaire" class="modal" @click.self="closeModal">
      <div class="modal-content">
        <span class="close" @click="closeModal">&times;</span>
        <h3>历史问卷</h3>
        <div class="questionnaire-content">
          <div v-for="(answer, questionIndex) in historyQuestionnaire.questionAndAnswer" :key="questionIndex">
            <p><strong>问题：</strong>{{ questionIndex + 1 }}、{{ Object.keys(answer)[0] }}</p>
            <p><strong>回答：</strong>{{ Object.values(answer)[0] }}</p>
          </div>
          <p><strong>问卷总结：</strong>{{ historyQuestionnaire.summary }}</p>
        </div>
      </div>

    </div>
    <!-- 修改后的预约弹窗 -->
  <div v-if="showBookingModal" class="modal" @click.self="closeBookingModal">
    <div class="modal-content booking-modal">
      <span class="close" @click="closeBookingModal">&times;</span>
      <div class="calendar-container">
        <!-- 左侧日历改为展开式 -->
        <div class="calendar-section">
          <h3>选择预约日期</h3>
          <div class="calendar-grid">
            <div class="calendar-header">
              <div v-for="day in ['日','一','二','三','四','五','六']" :key="day">{{ day }}</div>
            </div>
            <div class="calendar-body">
              <div 
                v-for="date in calendarDates"
                :key="date.date"
                class="calendar-day"
                :class="{
                  'disabled': date.disabled,
                  'selected': date.selected
                }"
                @click="selectDate(date)"
              >
                {{ date.day }}
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧时间选择 -->
        <div class="time-section">
          <h3>可选时间段（{{ selectedDate }}）</h3>
          <div v-if="availableTimes.length > 0" class="time-slots">
            <button 
              v-for="(time, index) in availableTimes" 
              :key="index"
              @click="selectTime(time)"
              :class="{ selected: selectedTime === time }"
            >
               {{ formatTimeDisplay(time) }}
            </button>
          </div>
          <div v-else>
                <p>暂无可用时间段。</p>
          </div>
        </div>
      </div>

      <!-- 咨询方式选择 -->
      <div v-if="selectedTime" class="consultation-type">
        <h3>选择咨询方式</h3>
        <div class="type-options">
          <button @click="selectConsultationType('线上')" :class="{ active: consultationType === '线上' }">线上</button>
          <button @click="selectConsultationType('线下')" :class="{ active: consultationType === '线下' }">线下</button>
        </div>
      </div>

      <button 
        v-if="consultationType" 
        class="confirm-btn"
        @click="handleOrderConfirmation"
      >
        确认预约
      </button>
    </div>
  </div>

    <!-- 新增确认提示弹窗 -->
    <div v-if="showConfirmDialog" class="modal" @click.self="showConfirmDialog = false">
      <div class="modal-content confirm-dialog">
        <p>{{ confirmMessage }}</p>
        <div class="dialog-buttons">
          <button @click="handleConfirm">{{ confirmType === '线上' ? '去支付' : '确定' }}</button>
          <button @click="showConfirmDialog = false">取消</button>
        </div>
      </div>
    </div>
   </div>
</template>

<script>
import { format, isBefore, startOfMonth, endOfMonth, eachDayOfInterval } from 'date-fns'
import NavBar from './NavBar.vue'; // 引入导航栏组件
export default {
    components: {
    NavBar
  },
  data() {
    return {
      isLoggedIn: localStorage.getItem("token") !== null,  // 判断是否登录
      role: localStorage.getItem("role") || "VISITOR",     // 获取用户角色，默认为来访者
      userName: localStorage.getItem("userName") || "用户", // 显示用户名
      regions: ['北京', '上海', '广州'],           // 可筛选的地区
      expertises: ['心理咨询', '焦虑管理', '情绪调节'],    // 可筛选的专长领域
      selectedRegion: 'all',                                // 默认选择的地区
      selectedExpertise: 'all',                            // 默认选择的专长领域
      consultants: [],                                     // 咨询师数据
      filteredConsultants: [],                             // 筛选后的咨询师数据
      appointments: [],                                    // 咨询师的预约记录
      showConsultantDetails: false,                         // 是否展示弹出框
      currentConsultant: {},                               // 当前查看的咨询师
      showHistoryQuestionnaire: false,                      // 是否展示历史问卷弹框
      historyQuestionnaire: {},                              // 历史问卷数据
      showBookingModal: false,
      selectedDate: new Date().toISOString().split('T')[0], // 默认今日
      availableTimes: [],
      selectedTime: null,
      consultationType: '',
      currentConsultantId: null,
      showConfirmDialog: false,
      confirmMessage: '',
      confirmType: '',
      paymentWindow: null,
      // 新增日历相关数据
      calendarDates: [],
      currentMonth: new Date(),
    };
  },
  created() {
    this.loadConsultants();
  },
  mounted() {
    this.generateCalendar();
  },
  methods: {
    // 加载咨询师数据
    loadConsultants() {
      const token = localStorage.getItem("token");
      const payload = { current: 0, pageSize: 15 };

      this.$axios.post('/user/consultation/list/page', payload,{
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json; charset=utf-8'
        }
      }).then(response => {
        this.consultants = response.data.content;
        //保存咨询师的id与名字用来预约记录展示
        const map = response.data.content.map(item => {
         return {
           userId: item.id,
           nickname: item.nickname
         };
       });
        console.log(map)
        map.forEach(item => {
           localStorage.setItem(item.userId,item.nickname);
        });
        console.log(localStorage.getItem("userId"));

        this.filteredConsultants = this.consultants;  // 默认展示所有咨询师
      }).catch(error => {
        console.error('获取咨询师信息失败', error);
      });
    },
    // 筛选咨询师
    filterConsultants() {
      this.filteredConsultants = this.consultants.filter(consultant => {
        return (this.selectedRegion === 'all' || consultant.region === this.selectedRegion) &&
               (this.selectedExpertise === 'all' || consultant.goodAt === this.selectedExpertise);
      });
    },
    
    // 预约咨询师
    bookAppointment(consultantId) {
      this.currentConsultantId = consultantId;
      this.showBookingModal = true;
      this.fetchAvailableTimes();
    },
    // 查看咨询师信息
    viewConsultant(consultant) {
      this.currentConsultant = consultant;
      this.showConsultantDetails = true;
    },
    // 关闭查看咨询师信息的弹框
    closeModal() {
      this.showConsultantDetails = false;
      this.showHistoryQuestionnaire = false; // 关闭历史问卷弹窗
    },
    // 用户注销
    logout() {
      localStorage.removeItem("token");
      localStorage.removeItem("role");
      localStorage.removeItem("userName");
      this.$router.push("/login");  // 注销后跳转到登录页面
    },
    // 跳转到登录页面
    goToLogin() {
      this.$router.push("/login");
    },
    // 查看历史问卷
    viewHistoryQuestionnaire() {
      const userId = localStorage.getItem("userId");
      const token = localStorage.getItem("token");

      this.$axios.get('/questionnaire/viewQuestionnaire', {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json; charset=utf-8'
        },
        params: {
          userId: userId
        }
      }).then(response => {
        this.historyQuestionnaire = response.data;
        this.showHistoryQuestionnaire = true;  // 展示弹窗
      }).catch(error => {
        console.error('获取历史问卷失败', error);
      });
    },
    // 生成日历
    generateCalendar() {
      const start = startOfMonth(this.currentMonth)
      const end = endOfMonth(this.currentMonth)
      const dates = eachDayOfInterval({ start, end })
      
      this.calendarDates = dates.map(date => {
        const day = format(date, 'd')
        const today = new Date()
        const todayString = format(today, 'yyyy-MM-dd'); // 只取日期部分，不考虑时间
        return {
          date: format(date, 'yyyy-MM-dd'),
          day,
          disabled: isBefore(date, today) && format(date, 'yyyy-MM-dd') !== todayString,
          selected: format(date, 'yyyy-MM-dd') === this.selectedDate
        }
      })
    },
    // 获取可选时间段
    async fetchAvailableTimes() {
      try {
        const token = localStorage.getItem("token");
        const response = await this.$axios.post('/order/selectTime', {
          consultantId: this.currentConsultantId,
          date: this.selectedDate
        }, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json; charset=utf-8'
          }
        });
        this.availableTimes = response.data;
      } catch (error) {
        console.error('获取时间段失败:', error);
        this.availableTimes = [];
      }
    },// 时间选择处理
    selectTime(time) {
      this.selectedTime = time;
    },
    // 选择日期
    selectDate(dateInfo) {
      if (dateInfo.disabled) return;
      this.selectedDate = dateInfo.date; // 更新选中的日期
      this.fetchAvailableTimes(); // 获取可用时间
      this.generateCalendar(); // 重新生成日历，以便更新视图
    },

    // 格式化时间显示
    formatTimeDisplay(fullTime) {
        //console.log(fullTime.split(' ')[1]);
      return fullTime.split(' ')[0].substr(0, 3) + fullTime.slice(-10);
    },
    // 修改时间解析方法
     parseTime(timeStr) {
    const date = this.selectedDate;
    console.log(date);
    const [startTime, ...timeParts] = timeStr.split(' ')
    const endTime = timeParts[1];

    console.log("endTime: ",endTime);

    return [
      `${date} ${startTime}:00`,
      `${date} ${endTime}:00`
    ]
  },

    // 选择咨询类型
    selectConsultationType(type) {
      this.consultationType = type;
    },

    // 处理订单确认
    handleOrderConfirmation() {
      this.confirmType = this.consultationType;
      this.confirmMessage = this.consultationType === '线上' 
        ? "您好，是否已与该咨询师确认时间/线上会议室，如已确认，请点击下方去支付，如未确认请先确认！"
        : "您好，是否已与该咨询师确认时间/地点，如未确认请先确认！";
       
      this.showConfirmDialog = true;
    },

    // 确认操作处理
    async handleConfirm() {
      this.showConfirmDialog = false;
      
      try {
        const orderData = await this.createOrder();
        const orderDataString = JSON.stringify(orderData);
        console.log("这里为转换的字符串：",orderDataString)
        const orderId = Number(orderDataString.match(/\d+/)[0]);
        console.log("订单id: ",orderId);
         // 检查返回的数据格式，确保包含 `orderId`
      if (!orderData || !orderId) {
       throw new Error('订单创建失败，未获取到有效的订单ID');
     }
        if (this.confirmType === '线上') {
          this.handleOnlinePayment(orderId);
        }
        console.log("confirmType是: ",this.confirmType)
        if(this.confirmType === '线下') {
            console.log("查看是否走入此判断")
          this.$message.success("等待咨询师确认预约中...可在我的预约中进行查看。");
          this.$router.push('/appointments');
        }
      } catch (error) {
        console.error('订单创建失败:', error);
    // 添加安全判断
    if (this.$message) {
      this.$message.error('预约失败，请稍后重试');
    } else {
      alert('预约失败，请稍后重试'); // 备用方案
    }
      }
    },

    // 创建订单
    async createOrder() {
      const [startTime, endTime] = this.parseTime(this.selectedTime);
      
      const token = localStorage.getItem("token");
      const userId = localStorage.getItem("userId");
      try {
      const response =await this.$axios.post('/order/create', {
        user_id: userId,
        consultant_id: this.currentConsultantId,
        start_time: startTime,
        end_time: endTime,
        fee: "120", // 假设固定费用，实际应从接口获取
        order_type: this.consultationType,
        remark: "要求私密会议室"
      }, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json; charset=utf-8'
        }
      });
      // 确保返回有效的数据
    if (!response || !response.data) {
      throw new Error('订单创建接口返回空数据');
    }
    

    return response.data;  // 返回正确的数据格式
    } catch (error) {
    console.error('创建订单请求失败:', error);
    throw new Error('创建订单失败');
  }
    },

    // 处理线上支付
    async handleOnlinePayment(orderId) {
      try {
        console.log("这里的orderId为：",orderId)
       
        const response = await this.$axios.post(`/order/payment?orderId=${orderId}`, null, {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem("token")}`,
            'Content-Type': 'application/json; charset=utf-8'
          }
        });
        // 获取返回的HTML报文
        const htmlContent = response.data; 
        const paymentWindow = window.open('', '_blank');
        paymentWindow.document.write(htmlContent);
        paymentWindow.document.close();
        
        
        // 监听窗口关闭
        const timer = setInterval(() => {
          if (paymentWindow.closed) {
            clearInterval(timer);
            this.$router.push('/appointments');
          }
        }, 500);
      } catch (error) {
        console.error('支付失败:', error);
        this.$message.error('支付流程启动失败');
      }
    },

    // 关闭预约弹窗
    closeBookingModal() {
      this.showBookingModal = false;
      this.resetBookingData();
    },

    // 重置预约数据
    resetBookingData() {
      this.selectedTime = null;
      this.consultationType = '';
      this.currentConsultantId = null;
    },

    //开始聊天
    chatWithConsultant(consultantId) { 
        console.error("咨询师id为：",consultantId);
      this.$router.push({
        path: '/messages',
        query: { targetId: consultantId }
    })
    } 

  }
};
</script>

<style scoped>
/* 整体清新、整洁的设计风格 */
body {
  font-family: 'Arial', sans-serif;
  background-color: #f7f7f7; /* 浅灰背景，给人干净、简洁的感觉 */
  color: #333;
  margin: 0;
  padding: 0;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 主容器 */
.main-container {
  width: 100%;
  max-width: 2200px;
  padding: 20px;
  background: linear-gradient(to right, #f1f1f1, #e0e0e0);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1); /* 轻微的阴影效果 */
  border-radius: 10px;
  box-sizing: border-box;
}

/* 导航栏样式 */
header {
  margin-bottom: 30px;
}

.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 2px solid #ddd; /* 细线分隔 */
}

.logo {
  font-size: 24px;
  font-weight: bold;
  color: #4D90FE; /* 明亮的蓝色 */
}

.nav-right {
  display: flex;
  align-items: center;
}

.nav-questionnaire {
  background-color: #4D90FE;
  color: white;
  padding: 9px 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.nav-btn {
  background-color: #4D90FE;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
  transition: background-color 0.3s;
  font-size: 16px;
}

.nav-btn:hover {
  background-color: #357AE8; /* 悬停时深蓝色 */
}

.dropdown {
  position: relative;
}

.dropbtn {
  background-color: #4D90FE;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.dropbtn:hover {
  background-color: #357AE8;
}

.dropdown-content {
  display: none;
  position: absolute;
  top: 100%;
  left: 0;
  background-color: #fff;
  min-width: 160px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
}

.dropdown:hover .dropdown-content {
  display: block;
}

.dropdown-content a {
  color: #333;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #f1f1f1;
}

/* 来访者主页 */
.visitor-main {
  margin-top: 20px;
}

.visitor-main h2 {
  font-size: 28px;
  color: #4D90FE; /* 明亮的蓝色 */
  margin-bottom: 20px;
  text-align: center;
}

/* 筛选部分 */
.filter {
  display: flex;
  margin-bottom: 20px;
  align-items: center; /* 保证标签和选择框对齐 */
}

.filter label {
  font-size: 14px;
  color: #555;
  margin-right: 10px; /* 增加适当间距 */
}

.filter select {
  padding: 8px 10px;
  border-radius: 5px;
  border: 1px solid #ddd;
  font-size: 14px;
}

.filter select:first-child {
  margin-right: 10px; /* 使两个选择框之间稍微留点空隙 */
}

/* 咨询师卡片 */
.consultant-card {
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  margin: 10px;
  width: 280px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  transition: box-shadow 0.3s, transform 0.3s;
}

.consultant-card:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-10px);
}

.consultant-image {
  width: 100%;
  height: auto;
  border-radius: 50%;
  margin-bottom: 15px;
}

.consultant-details h3 {
  font-size: 20px;
  color: #333;
}

.consultant-details p {
  font-size: 14px;
  color: #777;
  margin: 10px 0;
}

.consultant-actions button {
  background-color: #4D90FE;
  color: white;
  padding: 8px 12px;
  border: none;
  border-radius: 5px;
  margin-top: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.consultant-actions button:hover {
  background-color: #357AE8;
}

/* 未登录时页面 */
.noLogging-main {
  text-align: center;
  margin-top: 100px;
}

.noLogging-main h2 {
  font-size: 28px;
  color: #4D90FE;
}

.noLogging-main p {
  font-size: 18px;
  color: #777;
}
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  width: 80%;
  max-width: 600px;
}

.close {
  position: absolute;
  top: 10px;
  right: 20px;
  font-size: 30px;
  cursor: pointer;
}

button.nav-questionnaire {
  cursor: pointer;
}
/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.modal-content {
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  width: 80%;
  max-width: 600px;
  max-height: 80%; /* 设置弹窗最大高度 */
  overflow-y: auto; /* 启用滚动条 */
}

.close {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 30px;
  cursor: pointer;
  background-color: transparent;
  border: none;
}

h3 {
  text-align: center;
  color: #4D90FE;
  font-size: 22px;
}

.questionnaire-content {
  max-height: 400px;
  overflow-y: auto; /* 支持内容滚动 */
}

p {
  font-size: 16px;
}
/* 新增样式 */
.booking-modal {
  max-width: 800px;
  padding: 30px;
}

.calendar-container {
  display: flex;
  gap: 30px;
}

.calendar-section, .time-section {
  flex: 1;
}

.time-slots {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  //max-height: 300px;
  overflow-y: auto;
}

.time-slots button {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #fff;
  color: #333;
  cursor: pointer;
  white-space: nowrap; /* 防止时间换行 */
  visibility: visible;   /* 确保按钮是可见的 */
}

.time-slots button.selected {
  background: #4D90FE;
  color: white;
}

.consultation-type {
  margin-top: 20px;
}

.type-options {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.type-options button {
  padding: 10px 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #fff;
}

.type-options button.active {
  background: #4D90FE;
  color: white;
}

.confirm-btn {
  display: block;
  width: 100%;
  padding: 12px;
  margin-top: 20px;
  background: #4D90FE;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-dialog {
  text-align: center;
  padding: 30px;
}

.dialog-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.dialog-buttons button {
  padding: 8px 20px;
  min-width: 100px;
}
/* 新增日历样式 */
.calendar-grid {
  width: 300px;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 10px;
}

.calendar-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

.calendar-body {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
  padding-top: 10px;
}

.calendar-day {
  padding: 8px;
  text-align: center;
  cursor: pointer;
  border-radius: 4px;
  transition: background 0.3s ease, color 0.3s ease; /* 增加颜色过渡效果 */
}

.calendar-day:hover:not(.disabled) {
  background: #4D90FE;
}

.calendar-day.selected {
  background: #4D90FE;
  color: white;
}

.calendar-day.disabled {
  color: #ccc;
  cursor: not-allowed;
}
</style>
